package com.xuecheng.media.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.media.QueryMediaModel;
import com.xuecheng.api.media.model.MediaDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.SecurityUtil;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import com.xuecheng.media.convert.MediaConvert;
import com.xuecheng.media.entity.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.region}")
    private String regionId;
    //预览媒资
    public String getVODUrl(Long mediaId,Long companyId) {
    // 1.判断业务数据
        if (ObjectUtils.isEmpty(mediaId)) {
        ExceptionCast.cast(CommonErrorCode.E_100101);
    }
    // 2.根据媒资id获得媒资信息
    Media media = getById(mediaId);
        if (ObjectUtils.isEmpty(media)) {
        ExceptionCast.cast(CommonErrorCode.E_100104);
    }
    // 3.如果公司id不为空，对其进行判断
        if (!(ObjectUtils.isEmpty(companyId))) {
        if (!(ObjectUtils.nullSafeEquals(media.getCompanyId(), companyId))) {
            ExceptionCast.cast(CommonErrorCode.E_100108);
        }
    }

    String playUrl = getPlayUrl(media.getFileId());
    // 4.返回媒资的资源地址
        return playUrl;
    }
    //删除媒资
    @Override
    public boolean deleteMedia(Long mediaId) {
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Media::getId,mediaId);
        boolean remove = this.remove(wrapper);
        return remove;
    }
    //平台审核
    @Transactional
    public boolean auditMedia(MediaDTO mediaDTO) {
        Media media = MediaConvert.INSTANCE.dto2entity(mediaDTO);
        LambdaUpdateWrapper<Media> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Media::getAuditMind,media.getAuditMind());
        if (media.getAuditStatus().equals(AuditEnum.AUDIT_DISPAST_STATUS.getCode())){
            wrapper.set(Media::getAuditStatus,media.getAuditStatus());
        }
        else {
            wrapper.set(Media::getAuditStatus,media.getAuditStatus());
        }
        wrapper.eq(Media::getId,media.getId());
        boolean update = this.update(wrapper);
        return update;
    }

    private String getPlayUrl(String videoId) {

        String playUrl = "";
        try {
            DefaultAcsClient client =
                    AliyunVODUtil.initVodClient(regionId,accessKeyId,accessKeySecret);
            GetPlayInfoResponse response = AliyunVODUtil.getPlayInfo(client,videoId);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            if (!(ObjectUtils.isEmpty(playInfoList))) {
                GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
                playUrl = playInfo.getPlayURL();
            }
        } catch (Exception e) {
            ExceptionCast.cast(MediaErrorCode.E_140014);
        }
        return playUrl;
    }

    //添加媒资
    @Transactional
    public MediaDTO createMedia(MediaDTO dto) {
        Long companyId = SecurityUtil.getCompanyId();
        Media media = MediaConvert.INSTANCE.dto2entity(dto);
        String url = getPlayUrl(media.getFileId());
        //必须
        media.setBucket(dto.getBucket());
        media.setFilename(dto.getFilename());
        media.setFileId(dto.getFileId());
        media.setType(dto.getType());
        //非必须
        media.setUrl(url);
        media.setAuditStatus(AuditEnum.AUDIT_UNPAST_STATUS.getCode());
        media.setCompanyId(companyId);
        boolean save = this.save(media);
        if (!save){
            throw new RuntimeException("保存失败");
        }
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Media::getId,media.getId());
        Media one = this.getOne(wrapper);

        MediaDTO mediaDTO = MediaConvert.INSTANCE.entity2dto(one);

        return mediaDTO;
    }
    //查询媒资
    @Override
    public PageVO<MediaDTO> queryMediaList(PageRequestParams params, QueryMediaModel media, Long companyId) {
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Media::getCompanyId,companyId);
        List<Media> list = this.list(wrapper);
        //长度判断
        if (params.getPageSize()<1){
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }
        //页数判断
        if (params.getPageNo()<1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }
        //判断公司id
        if (ObjectUtils.isEmpty(companyId)){
            throw new RuntimeException("公司不能为空哦!");
        }
        LambdaQueryWrapper<Media> queryWrapper = new LambdaQueryWrapper<>();
        //审核状态条件
        queryWrapper.like(StringUtil.isNotBlank(media.getFilename()),Media::getFilename,media.getFilename());
        //课程名称条件
        queryWrapper.eq(StringUtil.isNotBlank(media.getType()),Media::getType,media.getType());
        if (!ObjectUtils.isEmpty(list)) {
            queryWrapper.eq(Media::getCompanyId, companyId);
        }
        if (!StringUtil.isBlank(media.getAuditStatus())){
            queryWrapper.eq(Media::getAuditStatus,AuditEnum.AUDIT_UNPAST_STATUS.getCode());
        }
        Page<Media> page = new Page<>(params.getPageNo(),params.getPageSize());
        Page<Media> mediaPage = this.page(page, queryWrapper);
        //Page<Media> mediaPage = this.page(pageResult);
        List<Media> records = mediaPage.getRecords();
        List<MediaDTO> dtolist = Collections.emptyList();
        dtolist = MediaConvert.INSTANCE.entitys2dtos(records);
        long total = mediaPage.getTotal();
        PageVO<MediaDTO> pageVO = new PageVO<>(dtolist, total, params.getPageNo(), params.getPageSize());
        return pageVO;
    }
}
